package com.orange.observerPatterns.event;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @Description: 事件中心
 */
public class EventHub {
    // 事件列表
    private HashMap<String, List<ClickEventSubscribe>> eventListenerList;

    public EventHub(HashMap<String,List<ClickEventSubscribe>> hashMap){
        this.eventListenerList = hashMap;
    }

    // 添加事件监听器
    public void addEventListener(Event event, ClickEventSubscribe listener) {
         //获取是否有事件注册
        List<ClickEventSubscribe> clickEventSubscribes = this.eventListenerList.get(event.name());
        if(clickEventSubscribes==null){
            ArrayList<ClickEventSubscribe> clickEventSubscribes1 = new ArrayList<>();
            clickEventSubscribes1.add(listener);
            eventListenerList.put(event.name(), clickEventSubscribes1);
            return;
        }

        //如果没有为空
        clickEventSubscribes.add(listener);
    }

    //推送方法
    public void push(Event event) {
        List<ClickEventSubscribe> clickEventSubscribes = this.eventListenerList.get(event.name());
        if(clickEventSubscribes==null){
            return;
        }
        for (ClickEventSubscribe clickEventSubscribe : clickEventSubscribes) {
            clickEventSubscribe.clickEventHappend();
        }
    }
}
